package testJdk.base.juc_test.test_atomic;

/**
 * @ClassName : learn_jdk.base.juc_test.test_atomic.CompareAndSet
 * @Description : 类描述
 * Created by cyd on 2021-10-22 11:43:58
 */
public class CompareAndSet {

    private int value = 0;

    public synchronized int get() {
        return value;
    }

    private synchronized int compareAndSwap(int expectedValve, int newValue) {
        int oldValve = value;
        if (oldValve == expectedValve) {
            value = newValue;
        }
        return oldValve;
    }

    public synchronized boolean compareAndSet(int expectedValve, int newValue) {
        return expectedValve == compareAndSwap(expectedValve, newValue);
    }
}

class CompareAndSetTest {
    public static void main(String[] args) {
        CompareAndSet compareAndSet = new CompareAndSet();
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int expectedValue = compareAndSet.get();
                    boolean flag = compareAndSet.compareAndSet(expectedValue,
                            (int) (Math.random() * 101));

                    System.out.println(flag +
                            ",expectedValue:" + expectedValue +
                            ",newValue:" + compareAndSet.get());
                }
            }).start();
        }
    }
}
